package controller;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import pojo.Cate;
import pojo.User;
import service.CateManagement;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;

/**
 * @author: zen
 * @date: 2020/9/8
 * @Title: ShowCate
 * @Description: 展示美食（列表广场或用户上传的美食）
 */
@WebServlet("/selectCate")
public class ShowCate extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter out = resp.getWriter();
        String cateId = req.getParameter("cateId");
        // 根据美食id查询美食信息
        if (!(cateId == null || cateId == "")) {
            Cate cate = CateManagement.getCateById(Integer.valueOf(cateId));
            JSONObject jsonObject = JSONObject.fromObject(cate);
            out.println(jsonObject.toString());
        } else {
            // 根据用户id查询美食信息
            HttpSession session = req.getSession();
            User user = (User) session.getAttribute("user");
            int id = user.getUserId();
            ArrayList<Cate> cates = CateManagement.getCatesByUserId(id);
            JSONArray jsonArray = JSONArray.fromObject(cates);
            out.println(jsonArray.toString());
        }
        out.flush();
        out.close();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
